package com.megvii.koala.tv.data;

import android.content.Context;

import com.megvii.corelib.util.SharedPreferenceTool;

/**
 * Created by linyue on 16/1/24.
 */
public class ServerManager
{
    public static final String KEY_SERVER_ADDRESS = "KEY_SERVER_ADDRESS";

    private Context context;

    private String address;

    private ServerManagerListener listener;

    public void init(Context context)
    {
        this.context = context;
        address = SharedPreferenceTool.getStringValueByKey(context, KEY_SERVER_ADDRESS, null);
    }

    public void release()
    {
        context = null;
        address = null;
    }

    public boolean setted()
    {
        return address != null && !address.isEmpty();
    }

    public String getAddress()
    {
        return address;
    }

    public void setAddress(String address)
    {
        this.address = address;
        persistent();
        if (listener != null)
        {
            listener.onAddressChanged(address);
        }
    }

    public void persistent()
    {
        if (address == null)
        {
            SharedPreferenceTool.removeStringValue(context, KEY_SERVER_ADDRESS);
        }
        else
        {
            SharedPreferenceTool.saveStringValue(context, KEY_SERVER_ADDRESS, address);
        }
    }

    public void setListener(ServerManagerListener listener)
    {
        this.listener = listener;
    }

    public interface ServerManagerListener
    {
        public void onAddressChanged(String address);
    }
}
